import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ${USER}
 * Date: ${YEAR}-${MONTH}-${DAY}
 * Time: ${TIME}
 */
public class Main {
    public static void main(String[] args) throws SQLException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("name>>");
        String name = scanner.nextLine();
        System.out.println("ID>>");
        int id = scanner.nextInt();

        //创建 dataSource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java5?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource) dataSource).setUser("root");
        ((MysqlDataSource) dataSource).setPassword("19705004009");

        //与数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        //构造sql(""中不需 ;)
//        String sql = "create table test(id int,name varchar(10))";
//        String sql = "insert into test values(?,?)";
          String sql = "select * from test";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
//        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,id);//通过用户输入id
        preparedStatement.setString(2,name);//通过用户输入name

        //把sql发给服务器返回值表示影响行数
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()) {
            System.out.println(resultSet.getInt("id"));
            System.out.println(resultSet.getString("name"));
        }

        //释放资源关闭连接
        resultSet.close();
        preparedStatement.close();
        connection.close();

    }
}